package com.shiwaixiangcun.customer.module.ticket

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterTicket
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.Data
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import kotlinx.android.synthetic.main.activity_ticket.*


/**
 * @author Administrator
 * 票务主页面
 */
class TicketActivity : BaseActivity() {

    private var list: MutableList<AdapterTicket.TicketSection>? = null
    private var tokenString: String? = null
    private var state: CollapsingToolbarLayoutState? = null
    private var adapterTicket: AdapterTicket? = null

    private enum class CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ticket)
        tokenString = AppSharePreferenceMgr.get(this, GlobalConfig.TOKEN, "") as String?
        initView()
        initData()
        refreshLayout.setOnRefreshListener {
            initData()
        }


    }


    /**
     * 初始化网络数据
     */
    private fun initData() {
        OkGo.get<String>(GlobalApi.getTickets)
                .params("page.pn", 1)
                .params("page.size", 30)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonObjCallBack<Data>>() {}.type
                        val responseEntity = Gson().fromJson<CommonObjCallBack<Data>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {

                                adapterTicket?.clearData()
                                if (refreshLayout.isRefreshing) {
                                    refreshLayout?.finishRefresh()
                                }
                                for (element in responseEntity.data.elements) {

                                    val header: AdapterTicket.TicketSection? = AdapterTicket.TicketSection(true, element.date)
                                    list!!.add(header!!)

                                    element.midwayLines
                                            .map { AdapterTicket.TicketSection(it) }
                                            .forEach { list!!.add(it) }

                                }
                                adapterTicket?.notifyDataSetChanged()
                            }
                            1006 -> {
                                refreshLayout?.finishRefresh()

                            }
                            else -> {
                                refreshLayout?.finishRefresh()
                            }
                        }
                    }

                })

    }

    /**
     * 设置视图
     */
    private fun initView() {
        toolbar_layout.setContentScrimColor(resources.getColor(R.color.ui_white))
        toolbar_layout.setStatusBarScrimColor(resources.getColor(R.color.transparent))

        list = ArrayList()
        adapterTicket = AdapterTicket(list)
        rv_ticket.layoutManager = LinearLayoutManager(this)
        rv_ticket.adapter = adapterTicket
        app_bar.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            when {
                verticalOffset == 0 -> {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED
                        tv_page_name.text = ""
                        back_left.setImageResource(R.drawable.back_white)
                    }


                }
                (Math.abs(verticalOffset) >= appBarLayout.totalScrollRange) -> {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {

                        tv_page_name.text = "汽车票"
                        back_left.setImageResource(R.mipmap.left_point)
                        state = CollapsingToolbarLayoutState.COLLAPSED
                    }

                }
                else -> {

                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
//                        playButton.setVisibility(View.GONE);//由折叠变为中间状态时隐藏播放按钮
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE


                }
            }
        }
        back_left.setOnClickListener { finish() }
        adapterTicket!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, _, position ->
            val item = adapter.data[position] as AdapterTicket.TicketSection
            if (item.isHeader) {
                return@OnItemClickListener
            } else {
                val bundle = Bundle()
                bundle.putLong("midWayId", item.t.midwayLineId)
                bundle.putLong("scheduleRecordId", item.t.recordId)
                readyGo(TicketBuyActivity::class.java, bundle)

            }
        }
    }


    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }
}
